package Collection;

import java.util.*;

/*
    Comparator比较器的使用：
    1.该比较器适用于临时比较的场合
    2.该比较器的方法为compare，第一个参数相当于compareTo里面的this对象
    comparator只适用于Arrays.sort和Collection.sort中
 */
public class ComparatorDemo {
    public static void main(String[] args) {
//        Person persons[]=new Person[3];
//        persons[0]=new Person("yao",22);
//        persons[1]=new Person("li",21);
//        persons[2]=new Person("wang",24);
//        System.out.println(Arrays.toString(persons));
//        Arrays.sort(persons, new Comparator<Person>() {
//            @Override
//            public int compare(Person o1, Person o2) {
//                return o1.age-o2.age;
//            }
//        });
//        System.out.println(Arrays.toString(persons));
        ArrayList<Person> arrayList=new ArrayList<>();
        arrayList.add(new Person("li",21));
        arrayList.add(new Person("hu",19));
        arrayList.add(new Person("wang",34));
        System.out.println(arrayList);
        arrayList.sort(new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                return o1.age-o2.age;
            }
        });
        System.out.println(arrayList);
    }
}
class Person{
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
